from datetime import datetime
from captcha.helpers import captcha_image_url
from captcha.models import CaptchaStore
from django.http import HttpResponse
from django.shortcuts import render, redirect

from django.urls import reverse

from App import models
from App.forms import RegisterForm, LoginForm, ManagerForm, Change_psd
from App.models import Article, Login, Article_type
from django.contrib import messages

from App.tools import BaiduPaginator

def index(request):
    return render(request,'index.html')

#左边导航栏
def public_left(request):
    if len(hidden) > 0:
        hiddens = hidden[0]
    else:
        hiddens = "hidden"
    return render(request,'public_left.html',locals())

list_data=[]
def public_header(request):
    if list_data:
        data=list_data[0]
        title = "论文爬取分析系统"
    else:
        list_data.append("未登录")
        data=list_data[0]
        title = "论文爬取分析后台管理系统"
    return render(request, 'public_header.html',locals())

#文章管理
hidden=[]
def public_main(request,cid=-1,page=1):
    if len(hidden)>0:
        hiddens=hidden[0]
    else:
        hiddens="hidden"
    product_count=Article_type.objects.count()
    if product_count==0:
        return render(request,'addType.html')
    products = Article_type.objects.all()
    #检索分类
    # 获取所有分类id
    postion = [cat.cid for cat in products]
    if request.method == "POST":
        cid = int(request.POST.get('cid', -1))
        keyword = request.POST.get('keyword', '')
        download1=request.POST.get('download1')
        download2=request.POST.get('download2')
        # 文章检索
        articles = Article.objects.filter(cid=cid,title__icontains=keyword).order_by("cid")
        if articles:
            if download1 and download2:
                articles = Article.objects.filter(cid=cid, download__gte=download1, download__lte=download2).order_by("cid")
            paginator = BaiduPaginator(articles, 10)
            return render(request,'wenzhang_seek.html',locals())

    else:
        if cid<0:
            first_product=products.first()# 查询第一个分类
            cid=first_product.cid# 第一个分类的id
            # 文章检索
        articles = Article.objects.filter(cid=cid).order_by("cid")
        #locals表示为传参数
        pos = postion.index(cid)
        # 分页
        if articles:
            paginator = BaiduPaginator(articles, 10)
            pager = paginator.page(page)
            pager.page_range = paginator.custom_range(paginator.num_pages, page, 5)
        return render(request,'wenzhang_xinwen.html',locals())


#注册页面
def login(request):
    error_name = ''
    count=Login.objects.count()
    if request.method=="POST":
        #用提交的数据生成表单
        form=RegisterForm(request.POST)
        username = request.POST.get('username')
        password = request.POST.get('password')
        regtime=request.POST.get('regtime')
        sex=request.POST.get('sex')
        user_check=models.Login.objects.filter(username=request.POST['username'])

        if user_check:
            # 注册失败
            error_name = '%s用户名已经存在了' % username
            # 返回到注册页面，并且把错误信息报出来
            return render(request, 'register.html',{'error_name':error_name})
        else:
            # 能通过验证返回True，否则返回False
            if form.is_valid():
                if len(regtime)==0:
                    current_time=datetime.now()
                user = models.Login.objects.create(id=count + 1, username=username, password=password, regtime=current_time,
                                                   sex=sex)
                user.save()
                return render(request, 'time.html', locals())
    return render(request,"register.html",locals())

#点击退出之后的页面
def login_user(request):
    list_data.clear()
    return render(request, 'login.html')

#登录页面
def register(request):
    form = LoginForm(request.POST)
    error_name=""
    if request.method=="POST":
        username=request.POST.get('name')
        password=request.POST.get('password')

        user_list = models.Login.objects.filter(username=username,password=password)
        if user_list:
            if form.is_valid():
                list_data.clear()
                list_data.append(username)
                hidden.clear()
                hidden.append("hidden")
                return render(request,'change_main.html')
            else:
                return render(request, 'login.html', locals())
        else:
            error_name = '%s用户名不存在,请重新输入' % username
            return render(request, 'login.html', locals())
    return render(request, 'login.html', locals())

# #文本编译器
#
# def edit_(request):
#     if request.method=="POST":
#         print(request.POST.get('content'))
#     return render(request,'article.html')


# def files(request):
#     return None

#修改密码
def change(request):
    error_name = ""
    error_s=""
    form=Change_psd(request.POST)
    if request.method=="POST":
        username=request.POST.get('name')
        password=request.POST.get('password')
        password_new=request.POST.get('new_password')
        #在数据库中查找是否存在
        user_exists=models.Login.objects.filter(username=username,password=password)
        #用户存在
        if user_exists:
            if form.is_valid():
                Login.objects.select_for_update().filter(username=username, password=password).update(password=password_new)
                error_s="修改成功"
            return render(request,'change_psw.html',locals())
        else:
            error_name = '%s用户名不存在,请重新输入' % username
            return render(request, 'change_psw.html', locals())
    return render(request,'change_psw.html')

#管理员系统设置
def system(request):
    return render(request,'xitong_set.html',locals())


def refresh(request):
    new_key = CaptchaStore.pick()
    res = captcha_image_url(new_key)
    return HttpResponse("点击")


def index2(request):
    return render(request,'index2.html')


def public_main2(request):
    return render(request,'xitong_set.html')


def articleType(request):
    if request.method=="POST":
        articleType=Article_type.objects.all()
    return render(request,'articleType.html',locals())


import os
def photo(request):
    img=['png','jpg']
    files=os.listdir("E:\\djangoProject\\Try\\static\\upload")
    filess=[]
    for i in files:
        filess.append("upload/"+i)
    Sum=len(filess)
    count=[]
    length=[]
    top=[]
    for i in range(Sum):
        if i>5:
            zheng=i//6;
            i=i-6*zheng;
            count.append(str(i*220)+"px")
            length.append(i+1)
            top.append(str((zheng+1)*250)+"px")
        else:
            count.append(str(i * 220) + "px")
            length.append(i * 220)
            top.append("200px")
    user2 = zip(filess,count,length,files,top)
    return render(request,'photo.html',locals())


def change2(request):
    return render(request,'change.html')

#管理员登录验证
def manager(request):
    errors=""
    if request.method=="POST":
        form = ManagerForm(request.POST)
        manager_name=request.POST.get('manager_name')
        password=request.POST.get('password')
        #获取数据库中的管理员信息
        manager_exsist=models.Manager.objects.filter(user_manager=manager_name,password=password)
        if manager_exsist:
            if form.is_valid():
                list_data.clear()
                list_data.append(manager_name + "管理员")
                hidden.clear()
                hidden.append("visible")
                return redirect(reverse('App:index'))
        else:
            name = models.Manager.objects.filter(user_manager=manager_name)
            if name:
                info=models.Manager.objects.get(user_manager=manager_name)
                if info.password != password and info.user_manager == manager_name:
                    errors = '密码不正确,请重新输入'
                    return render(request, 'manager.html', locals())
            else:
                if len(manager_name)!=0:
                    errors="%s用户不存在" % manager_name
                    return render(request, 'manager.html', locals())
    return render(request,'manager.html',locals())


def data_input(request):
    return render(request,'addType.html')
from pyecharts.charts import Bar, Scatter
from pyecharts import options as opts
def main_data(request,cid):
    if request.method=="GET":
        #通过主键找到名称
        title_object=Article.objects.filter(cid=cid)
        name=Article_type.objects.get(cid=cid).pname
        all = {}
        for i in title_object:
            all.update({i.title:i.download})
        #按照下载量进行降序排序
        d_order = sorted(all.items(), key=lambda x: x[1], reverse=True)
        title=[]
        download=[]
        for j in d_order:
            title.append(j[0])
            download.append(j[1])
        bar = (
            Bar()
                .add_xaxis(title[:10])
                .add_yaxis(name + "类型论文", download[:10], category_gap="30%")
                .set_global_opts(title_opts=opts.TitleOpts(title="文章下载量显示"),
                                 xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-90)),
                                 legend_opts=opts.LegendOpts(pos_left=300),
                                 yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(formatter="{value} /篇")), )
        )
        # bar.render_notebook()#在Notebook中进行渲染图像
        thml = "E:\\djangoProject\\Try\\templates\\" + name + ".html"
        bar.render(thml)  # 在本地生成静态网页
        return render(request, thml)
    return HttpResponse("ok")

import pyecharts.options as opts
from pyecharts.charts import Pie
def download(request,cid):
    if request.method=="GET":
        #通过主键找到名称
        title_object=Article.objects.filter(cid=cid)
        title=Article_type.objects.get(cid=cid)
        download=[]
        x_data=[]
        for i in title_object:
            download.append(i.download)
            x_data.append(str(i.download))
        download.sort(reverse=True)
        #获取最大下载量
        max=download[0]
        range=max//1000
        d1=[]
        d1_name=[]
        while(range>=0):
            count=0
            for i in download:
                if i>range*1000 and i<(range+1)*1000:
                    count=count+1
            d1.append(count)
            d1_name.append(str(range*1000)+"-"+str((range+1)*1000)+"次")
            range-=1
        thml = "E:\\djangoProject\\Try\\templates\\下载范围展示.html"

        c = (
            Pie()
                .add("", [list(z) for z in zip(d1_name, d1)])
                .set_global_opts(title_opts=opts.TitleOpts(title="\n"+str(title.pname)+"类型论文下载范围展示"))
                .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}篇"))
                .render(thml)
        )
        return render(request,thml)

from pyecharts.charts import Line
def publish(request,cid):
    title = Article_type.objects.get(cid=cid)
    # 通过主键得到一个对象结果集
    title_object = Article.objects.filter(cid=cid)
    time_=[]
    #取日期的年份
    for i in title_object:
       time_.append(int(str(i.time)[:4]))
    #从小到大排序
    time_.sort()
    num=(time_[-1]-time_[0])+1
    d1=[]
    d2=[]
    count_time = time_[0]
    while(num>0):
        count=0
        for i in time_:
            if i==count_time:
                count=count+1
        d1.append(count)
        d2.append(str(count_time)+"年")
        num=num-1
        count_time=count_time+1
    thml = "E:\\djangoProject\\Try\\templates\\时间趋势展示.html"
    (
        Line(init_opts=opts.InitOpts(width='1000px', height='500px'))  # 设置画布大小
            .add_xaxis(d2)
            .add_yaxis('论文发布数量年度趋势', d1)
            .set_global_opts(title_opts=opts.TitleOpts(title=title.pname+"年度趋势图"))
    ).render(thml)
    return render(request,thml)

#管理员用户管理
def manager_user(request):
    users = Login.objects.all()
    return render(request,'userManager.html',locals())